package myJs.cps

import myJs.myPkg.rSelect.{Select, SelectOption}
import myJs.myPkg.reactHookForm._
import japgolly.scalajs.react._
import myJs.myPkg.Hooks._
import japgolly.scalajs.react.vdom.all._
import myJs.Utils._

import scala.collection.immutable.SeqMap
import scala.scalajs.js
import scala.scalajs.js.JSConverters._

/** Created by yz on 21/1/2022
  */
object PureRSelectMulCp {

  case class Props(
      optionMap: SeqMap[String, String],
      onChange: List[String] => Callback,
      name: String = "",
      value: List[String],
      registerOptions: RegisterOptions = RegisterOptions()
  ) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    val useController = ReactHookForm.useController(options =
      UseControllerOptions(
        name = props.name,
        rules = props.registerOptions,
        defaultValue = props.value
      )
    )

    val field = useController.field
    val fieldState = useController.fieldState
    object FTool {

      def onChange = (sos: List[SelectOption]) => {
        val vs = sos.map(_.value)
        field.onChange(vs.toJSArray)
        props.onChange(vs)
      }

    }

    useEffect(
      Callback {
        if (props.value != field.value.asInstanceOf[js.Array[String]].toList) {
          field.onChange(props.value.toJSArray)
        }
      },
      List(props.value)
    )

    val options = props.optionMap.map { case (k, v) =>
      SelectOption(value = k, label = v)
    }.toList
    val selectOptions = props.value.map { x =>
      SelectOption(value = x, label = x)
    }
    div(
      Select(
        onChange = FTool.onChange,
        options = options,
        placeholder = "click to choose",
        name = field.name,
        value = selectOptions,
        ref = field.ref,
        isMulti = true
      ),
      if (fieldState.error.isDefined) {
        small(
          className := "help-block",
          fieldState.error.get.message
        )
      } else EmptyVdom
    )

  }

}
